// EOODBCConnection.cs
//
//  Copyright (C) 2008 Whitemice Consulting
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//
using System;
using System.Data;
using System.Data.Odbc;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using log4net;

namespace Whitemice.EOMono
{
  public class EOODBCConnection : EOSQLConnection, IEOSQLConnection
  {   
    protected OdbcConnection connection;
    
    public EOODBCConnection(string _dsn)
    {
			try 
			{
			  connection = new OdbcConnection(_dsn);
			  connection.Open();
			} catch (Exception _exception)
			  {
			    Console.WriteLine("Failure connecting to database");
			    Console.WriteLine("{0}\n{1}\n", _exception.Message, _exception.StackTrace);
			    throw _exception;
			  }
			EOManager.Log.Debug("Database Connected");
    }
    
    public IDbConnection Connection
    { get { return connection; } }
    
		public void Close()
		{
			connection.Close();
			connection = null;
		}
    
    public object LastSerialId(EOSQLCommand command)
    {
      object result;
      System.Data.IDbCommand magicCommand = connection.CreateCommand();
      magicCommand.CommandText = string.Format("{0} {1}",
                                   "SELECT DBINFO(\'sqlca.sqlerrd1\')",
                                   "FROM systables where tabid = 1");
      Console.WriteLine("SQL:{0}", magicCommand.CommandText);
      EOManager.Log.DebugFormat("SQL:{0}", magicCommand.CommandText);
      result = magicCommand.ExecuteScalar();
      if (result == null)
      {
        EOManager.Log.Error("Serial id on magick entity after insert is NULL!");
        throw new Exception("Serial id on magick entity after insert is NULL!");
      } else
        {
          EOManager.Log.DebugFormat("New Serial value is {0}.", result);
        }
      magicCommand.Dispose();
      magicCommand = null;
      return result;
    } // end LastSerialId
    
    public void Begin()
		{
		}
		
		public void Rollback()
		{
    }
    
    public void Commit()
    {
    }
  }
}
